package org.qtk.server;

import java.util.List;
import java.util.Map;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

public class WebApp {

	private static ServletContext context;
	static {
		context = new ServletContext();

		SAXParserFactory factory = SAXParserFactory.newInstance();
		try {
			SAXParser sax = factory.newSAXParser();
			WebHandler handler = new WebHandler();
			sax.parse(Thread.currentThread().getContextClassLoader()
					.getResourceAsStream("web.xml"), handler);

			// key:servlet-name ------ value:servlet-class
			Map<String, String> servlet = context.getServlet();
			for (Entity entity : handler.getEntityList()) {
				servlet.put(entity.getName(), entity.getClz());
			}

			// key:url-pattern ------ value:servlet-name
			Map<String, String> mapping = context.getMapping();
			for (Mapping mapp : handler.getMappingList()) {
				List<String> urls = mapp.getUrlPattern();
				for (String url : urls) {
					mapping.put(url, mapp.getName());
				}
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static String getServlet(String url) {
		if ((null == url) || (url = url.trim()).equals("")) {
			return null;
		}
		return context.getServlet().get(context.getMapping().get(url));
	}
}
